//
//  MTFindOtherVC.m
//  met
//
//  Created by 李晓俊 on 2019/6/14.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTFindOtherVC.h"
#import "HighLightButton.h"
#import <UShareUI/UShareUI.h>
#import "MTYaoQingView.h"
#import "MTShouhuView.h"
@import Mapbox;


@interface MyCustomPointAnnotation2 : MGLPointAnnotation
@property (nonatomic, assign) BOOL willUseImage;
@property (nonatomic,strong) NSString *userId;
@property (nonatomic,strong) FindModel *model;
@end

@implementation MyCustomPointAnnotation2
@end

@interface MGLCustomAnnotationView2 : MGLAnnotationView
@property (nonatomic,strong) UIImageView *bg;
@property (nonatomic,strong) UIImageView *img;
@end

@implementation MGLCustomAnnotationView2
@end

@interface MTFindOtherVC ()<MGLMapViewDelegate,UMSocialShareMenuViewDelegate>
@property (nonatomic,strong) MGLMapView *mapView;
@property (nonatomic, copy) NSArray *annotationsArray;


@property (nonatomic,strong) HighLightButton *backBut;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UIView *findView2;
@property (nonatomic,strong) HighLightButton *siliaoBut;
@property (nonatomic,strong) HighLightButton *zhuyeBut;
@property (nonatomic,strong) HighLightButton *liaotaBut;
@property (nonatomic,strong) NSString *jumpUrl;
@end

@implementation MTFindOtherVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSURL *url = [NSURL URLWithString:@"mapbox://styles/yuzhong/cjwxxkt0s35um1co5ay5dg4mh"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.mapUrl]];

    _mapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) styleURL:url];
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //    [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.9,116.4)
    //                       zoomLevel:14
    //                        animated:NO];
    _mapView.logoView.hidden = YES;
    _mapView.attributionButton.hidden = YES;
    
    _mapView.delegate = self;
    //是否旋转地图
    _mapView.rotateEnabled  = NO;
    _mapView.pitchEnabled  = NO;
    _mapView.scrollEnabled  = NO;
    _mapView.zoomEnabled  = NO;

    
    _mapView.userTrackingMode = MGLUserTrackingModeFollow;
    _mapView.showsUserHeadingIndicator = YES;
    //显示用户位置
    _mapView.showsUserLocation  = NO;
    [self.view addSubview:_mapView];

    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    self.jumpUrl = @"";
 
}
- (UIView*)UMSocialParentView:(UIView*)defaultSuperView
{
    return [UIApplication sharedApplication].keyWindow;
}


- (void)createFindView{
    if (self.findView2) {
        [self.findView2 removeFromSuperview];
        self.findView2 = nil;
    }
    self.findView2 = [[UIView alloc] initWithFrame:CGRectMake(20, 20+StatusHeight, kScreenWidth-20, 44)];
    if (self.nameLabel) {
        [self.nameLabel removeFromSuperview];
        self.nameLabel = nil;
    }
    self.nameLabel  = [UILabel new];
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowBlurRadius = 3.0;
    shadow.shadowOffset = CGSizeMake(0, 3);
    shadow.shadowColor = KBlackColor;
    NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",self.chooseModel.nickName] attributes:@{NSShadowAttributeName:shadow}];
    self.nameLabel.attributedText = attributedText;
    
    [self.findView2 addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(0);
    }];
    
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.font = CLRudeCircleTextFont(30);
    self.nameLabel.textColor = KMainColor;
    
    [self.mapView addSubview:self.findView2];
//    .titleView = ;
    
    if (self.backBut) {
        [self.backBut removeFromSuperview];
        self.backBut = nil;
    }
    self.backBut = [[HighLightButton alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-23.5, kScreenHeight-49-BottomHeight-60, 47, 49)];
    [self.backBut setImage:[UIImage imageNamed:@"大返回"]  forState:UIControlStateNormal];
    [self.backBut addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:self.backBut];
   
    self.liaotaBut = [[HighLightButton alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-44, kScreenHeight-100-87-BottomHeight-30, 87, 87)];
    [self.mapView addSubview:self.liaotaBut];
   
    [self.liaotaBut setImage:[UIImage imageNamed:@"去撩她"] forState:UIControlStateNormal];
    [self.liaotaBut addTarget:self action:@selector(liaotaClick) forControlEvents:UIControlEventTouchUpInside];
    
    //    if (self.zhuyeBut) {
    //        [self.zhuyeBut removeFromSuperview];
    //        self.zhuyeBut = nil;
    //    }
    self.zhuyeBut = [[HighLightButton alloc] initWithFrame:CGRectMake(60, kScreenHeight-100-87-BottomHeight-30, 87, 87)];
    [self.mapView addSubview:self.zhuyeBut];
   
    [self.zhuyeBut setImage:[UIImage imageNamed:@"主页"] forState:UIControlStateNormal];
    [self.zhuyeBut addTarget:self action:@selector(homeClick) forControlEvents:UIControlEventTouchUpInside];
    self.siliaoBut = [[HighLightButton alloc] initWithFrame:CGRectMake(kScreenWidth-60-87, kScreenHeight-100-87-BottomHeight-30, 87, 87)];
    [self.mapView addSubview:self.siliaoBut];
   
    [self.siliaoBut setImage:[UIImage imageNamed:@"私聊"] forState:UIControlStateNormal];
    [self.siliaoBut addTarget:self action:@selector(siliaoClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    if ([[NSString stringWithFormat:@"%@",self.chooseModel.isMutual]isEqualToString:@"1"]) {
        //已经关注了
        self.liaotaBut.hidden = YES;
        self.siliaoBut.hidden = NO;
    }else {
        self.liaotaBut.hidden = NO;
        self.siliaoBut.hidden = YES;
    }
    if ([[NSString stringWithFormat:@"%@",self.chooseModel.createType] isEqualToString:@"1"]) {
        //用户
        self.zhuyeBut.hidden = NO;
        self.liaotaBut.centerX = self.siliaoBut.centerX;
    }else {
        self.zhuyeBut.hidden = YES;
        self.liaotaBut.centerX = self.view.centerX;
    }
}
- (void)homeClick{
    if (self.home) {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.home(@"1");
    }
}
//取消选中
- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)liaotaClick {
    if (self.liaota) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *liaota = [userDefault objectForKey:@"liaota"];
        if ([liaota isEqualToString:@"1"]) {
            [self daojishiwanbi];
        }else {
            MTShouhuView *okView = [[MTShouhuView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            okView.headImage.image = [UIImage imageNamed:@"quliaota"];
            okView.bgView.backgroundColor = KMainColor;
            okView.goButClick = ^(NSString *  s) {
    //            [self dismissViewControllerAnimated:YES completion:nil];
    //            self.liaota(@"1");
                [self daojishiwanbi];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:okView];
        }
    }
}
- (void)daojishiwanbi {
  
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
        [dataUser setObject:@"1" forKey:@"liaota"];
        [dataUser synchronize];
        
        if (code == 1) {
            [self dismissViewControllerAnimated:YES completion:nil];
            self.liaota(data);
        }else {
            //车票不足的话
            MTShouhuView *okView = [[MTShouhuView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            okView.headImage.image = [UIImage imageNamed:@"chepiaobuzu"];
            okView.bgView.backgroundColor = KMainColor;
            okView.goButClick = ^(NSString *  s) {
                [self yaoqing];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:okView];
            
//            [self.view maketishiToast:data];
        }
    };
     if ([[NSString stringWithFormat:@"%@",self.chooseModel.createType] isEqualToString:@"1"]) {
         //用户
         [acc findStoryByTicketStoryId:self.chooseModel.storyId];
     }else {
        [acc findStoryByStoryId:self.chooseModel.storyId];
     }
}


- (void)siliaoClick {
    if (self.siliao) {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.siliao(@"1");
    }
}


//------------------------地图-------------------

#pragma mark MGLMapViewDelegate
- (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
    ///地图加载完成时加载大头针
    NSMutableArray  *pointArr = [NSMutableArray new];
    
    MyCustomPointAnnotation2 *pointAnnotation = [[MyCustomPointAnnotation2 alloc] init];
    pointAnnotation.model = self.chooseModel;
    pointAnnotation.willUseImage = YES;
    pointAnnotation.coordinate = CLLocationCoordinate2DMake([[NSString stringWithFormat:@"%@",self.chooseModel.lat] doubleValue], [[NSString stringWithFormat:@"%@",self.chooseModel.lng] doubleValue]);
    [pointArr addObject:pointAnnotation];
    
    [self.mapView addAnnotations:pointArr];
    [self createFindView];
    [_mapView setCenterCoordinate:pointAnnotation.coordinate
                             zoomLevel:14
                              animated:NO];
}

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        MGLUserLocationAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
        if (annotationView == nil) {
            annotationView = [[MGLUserLocationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
            [annotationView setFrame:CGRectMake(0, 0, 72, 72)];
            //            [annotationView setBackgroundColor:[UIColor redColor]];
            
            UIImageView *bg = [UIImageView new];
            bg.image = [UIImage imageNamed:@"椭圆 1"];
            [annotationView addSubview:bg];
            [bg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.bottom.mas_equalTo(0);
            }];
            
            UIImageView *img = [UIImageView new];
            [img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",KUSER.portraitMap]] placeholderImage:[UIImage imageNamed:@"椭圆 1"]];
            
            [annotationView addSubview:img];
            [img mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.mas_equalTo(8);
                make.right.bottom.mas_equalTo(-8);
            }];
            img.layer.cornerRadius = 28.f;
            img.layer.masksToBounds= YES;
            
            annotationView.layer.cornerRadius = 36.f;
            annotationView.layer.masksToBounds= YES;
            //            annotationView.layer.borderColor  = [UIColor blackColor].CGColor;
            //            annotationView.layer.borderWidth  = 1.f;
            //            annotationView.layer.borderColor  = [UIColor whiteColor].CGColor;
            //            annotationView.layer.borderWidth  = 5.f;
        }
        return annotationView;
        
        return nil;
    }
    if (![annotation isKindOfClass:[MGLPointAnnotation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MyCustomPointAnnotation2 class]]) {
        MyCustomPointAnnotation2 *castAnnotation = (MyCustomPointAnnotation2 *)annotation;
        
        MGLCustomAnnotationView2 *annotationView = (MGLCustomAnnotationView2 *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
        //        MGLCustomAnnotationView2 *annotationView = [[MGLCustomAnnotationView2 alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
        //        [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
        FindModel *model =  castAnnotation.model;
        
        if (annotationView == nil) {
            annotationView = [[MGLCustomAnnotationView2 alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
            //            annotationView = (MGLCustomAnnotationView2*) annotationView;
            [annotationView setFrame:CGRectMake(0, 0, 72, 72)];
            
            annotationView.bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 72, 72)];
            annotationView.bg.image = [UIImage imageNamed:@"玩家"];
            [annotationView addSubview:annotationView.bg];
            //            [bg mas_makeConstraints:^(MASConstraintMaker *make) {
            //                make.left.right.top.bottom.mas_equalTo(0);
            //            }];
            annotationView.img = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 56, 56)];
            //            [img mas_makeConstraints:^(MASConstraintMaker *make) {
            //                make.top.left.mas_equalTo(6);
            //                make.right.bottom.mas_equalTo(-6);
            //            }];
            [annotationView addSubview:annotationView.img];
            
            annotationView.img.contentMode = UIViewContentModeScaleAspectFill;
            [annotationView.img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model.portraitMap]] placeholderImage:[UIImage imageNamed:@"椭圆 1 拷贝 7"]];
            annotationView.img.layer.cornerRadius = 28;
            annotationView.img.layer.masksToBounds= YES;
            annotationView.layer.cornerRadius = 36;
            annotationView.layer.masksToBounds  = YES;
            
        }
        return annotationView;
        
    }
    MGLAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
    if (annotationView == nil) {
        annotationView = [[MGLAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
        [annotationView setFrame:CGRectMake(0, 0, 60, 60)];
        [annotationView setBackgroundColor:[UIColor redColor]];
        
        annotationView.layer.cornerRadius = 10.f;
        annotationView.layer.masksToBounds= YES;
        annotationView.layer.borderColor  = [UIColor whiteColor].CGColor;
        annotationView.layer.borderWidth  = 5.f;
    }
    return annotationView;
}
- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MyCustomPointAnnotation2 class]]) {
        MyCustomPointAnnotation2 *castAnnotation = (MyCustomPointAnnotation2 *)annotation;
        if (!castAnnotation.willUseImage) {
            return nil;
        }
    }
    MyCustomPointAnnotation2 *castAnnotation = (MyCustomPointAnnotation2 *)annotation;
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"camera"];
    
    if ([castAnnotation.userId isEqualToString:@"1"]) {
        UIImage *image = [UIImage imageNamed:@"发现"];
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];
        
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"camera2"];
    }else {
        UIImage *image = [UIImage imageNamed:@"椭圆 1 拷贝 7"];
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"camera"];
    }
    return annotationImage;
}

///是否显示气泡
-(BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id<MGLAnnotation>)annotation {
    return NO;
}
///完成加载大头针
- (void)mapView:(MGLMapView *)mapView didAddAnnotationViews:(NSArray<MGLAnnotationView *> *)annotationViews {
    //    [mapView showAnnotations:self.annotationsArray edgePadding:UIEdgeInsetsMake(100, 50, 100, 50) animated:YES];
}


//选中大头针
- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id<MGLAnnotation>)annotation {
 }
//取消选中
- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id<MGLAnnotation>)annotation {
}


//-------------------------地图---------------------






- (void) yaoqing {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            if ([[NSString stringWithFormat:@"%@",[data objectForKey:@"model"]]isEqualToString:@"1"]) {
            }else {
                //邀请链接
                NSString *url = [NSString stringWithFormat:@"%@",[data objectForKey:@"content"]];
                self.jumpUrl = url;
                [self shareClick];
            }
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findOthers:@"10"];
}



- (void)shareClick {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    MTYaoQingView *yao = [[MTYaoQingView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    yao.codeView.image = [self createCode];
    
    UIImage *img = [self makeImageWithView:yao withSize:CGSizeMake(375, 667)];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon"];
    [shareObject setShareImage:img];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (UIImage *)createCode{
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //设置过滤器默认属性
    [qrImageFilter setDefaults];
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    // 字符串可以随意换成网址等
    NSString *url = self.jumpUrl;
    
    NSData *qrImageData = [url dataUsingEncoding:NSUTF8StringEncoding];
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    //设置过滤器的 输入值 ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文 (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon108"];
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    //设置图片
    return  finalyImage;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}

@end
